#!/usr/bin/env python
import os, sys,requests
from lisn_utils import *

sys.path.append('../')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dblisn.settings")

from apps.data.models import Data, DataType, DataDate

path_gps = '/data1/gps/'
path_mag = '/data1/magnetometer/'
path_mag_montecillo = '/home/cesar/isr/magnetometer/'
path_mag_jro = '/chroot/home/cesar/isr/magnetometer_jro/'

def max_label(s, num=8):
    '''
    '''
    if len(s)>8:
        return '%s...' % s[:8]
    else:
        return s

def plt_error(msg):
    '''
    Plot an empty image with the given msg
    '''
    
    fig  = MyFigure(figname='web', figsize=(4, 3))
    fig.figure.text(0.5, 0.5, msg, ha='center')
    return fig

def plt_availability(**kwargs):
    '''
    Plot availability
    kwargs: station, datatype, network, dt1, dt2, output
    '''

    dtype = kwargs.get('dtype', None)
    dt1 = kwargs.get('dt1', None)
    dt2 = kwargs.get('dt2', dt1)
    station = kwargs.get('station')
    network = kwargs.get('network')    
    output = kwargs.get('output')
    country = kwargs.get('country')
    
    if dtype is None or dt1 is None:
        fig = plt_error('Invalid parameters')
        if output=='web':
            return fig.show()
        else:
            print 'Invalid parameters'
            return
    
    if dt1: dt1 = GPSDateTime(dt1)
    if dt2: dt2 = GPSDateTime(dt2)

    if dt1==dt2 or (dt2-dt1)/(60*60*24)<=10: 
        dt1=dt2-timedelta(30)

    days = int((dt2-dt1)/(60*60*24))+1
    dts= [(dt1+(24*60*60)*x).datetime.date() for x in xrange(days)]
    dts_ticks= [(dt1+(24*60*60)*x).datetime for x in xrange(0, days, days/8)]
    xticks_minor = range(0, days, days/8)
    xlabels_minor = [dt.strftime('%d %b') for dt in dts_ticks]
    xticks_major = []
    xlabels_major = []
    year = dt1.year
    for dt,x in zip(dts_ticks, xticks_minor):
        if dt.year==year:
            xticks_major.append(x)
            xlabels_major.append(dt.strftime('%Y'))
            year += 1
   
    qdtype = DataType.objects.get(alias=dtype)    
    qdata = Data.objects.select_related().filter(datatype=qdtype.pk)
    
    if network:
        qdata = qdata.filter(instrument__network__in=network.split(','))
    if country:
        qdata = qdata.filter(instrument__station__country__in=country.split(','))
    if station:
        qdata = qdata.filter(instrument__code__in=station.split(','))
    
    qdata = qdata.order_by('instrument__station__name').iterator()
    dummy = [0.1 for x in range(days)]
    data = []
    sites = []

    for q in qdata:      
        vdates = DataDate.objects.filter(data_id=q.pk, date__in=dts).values_list('date', flat=True)
        dum = [0.9 if dt in vdates else 0.1 for dt in dts]
        if True or 0.9 in dum:
            sites.append(max_label(q.instrument.station.name))
            data.append(dummy)
            data.append(dum)
    if len(data)==0 and output=='web':
        fig = plt_error('Sorry no results for your query')        
        return fig.show()
    
    data.append(dummy)
    sites.reverse()
    data.reverse()
    height = 1+0.18*len(data)
    fig  = MyFigure(figname=output, figsize=(6, height))    
    ax = fig.add_axes(xlim=(0, days),
                      ylim=(0, 2*len(sites)+1),
                      #xticks=xticks,
                      #xticklabels=xlabels,
                      yticks=[i*2+1.5 for i in range(len(sites))],
                      yticklabels=sites,
                      #xlabel=dt1.year,
                      #ylabel='',
                      )

    fig.py.pcolor(fig.py.np.array(data), cmap=fig.py.cm.Blues, axes=ax.ax, vmin=0, vmax=1)    

    ax.ax.grid(True)    
    ax.ax.xaxis.grid(False)
    ax.ax.set_xticks(xticks_minor, minor=True)
    ax.ax.set_xticklabels(xlabels_minor, size=8, minor=True)
    ax.ax.set_xticks(xticks_major)
    ax.ax.set_xticklabels(xlabels_major, size=8)
    ax.ax.xaxis.set_tick_params(which='major', pad=15)
    ax.ax.set_xlim(0, days)
    
    ax.set_yticks(size=8)
    ax.set_labels()        
    fig.suptitle('%s files' % qdtype.name, size=10)
    if len(sites)==1:
        fig.adjust(top=0.85, bottom=0.3, right=0.95)
    elif len(sites)<=2:
        fig.adjust(top=0.88, bottom=0.2, right=0.95)
    elif len(sites)<=8:
        fig.adjust(top=0.9, bottom=0.15, right=0.95)
    elif len(sites)<=20:
        fig.adjust(top=0.95, bottom=0.1, right=0.95)
    else:
        fig.adjust(top=0.96, bottom=0.05, right=0.95)

    if output=='web':
        return fig.show()
    elif output:
        fig.figure.savefig(output)
    else:
        fig.show()

def plt_mag(code, date, output=None, scale=None):
    '''
    '''
    
    if code is None:
        fig = plt_error('Invalid parameters')
        if output=='web':
            return fig.show()
        else:
            print 'Invalid parameters'
            return
    
    if date is not None:
        dt = GPSDateTime(date).datetime
    else:
        dt = GPSDateTime().now().datetime
    
    codes = [s.strip() for s in code.split(',') if s]
    fig = MyFigure(len(codes), 1, figsize=(6,len(codes)+1.5), figname=output)
    for code in codes:        
        req = requests.get('http://localhost/django/utils/station/', 
                          params={'code':code, 'instrument':'magnetometer'})
        st = req.json()
        qdata = Data.objects.select_related().filter(datatype__pk=1, 
                                                     instrument__code=code)
        if qdata:
            if date:
                filename = '%s_%s.min.gz' % (code, dt.strftime('%y%m%d'))
                path = os.path.join(path_mag, qdata[0].instrument.network, code, dt.strftime('%Y/%m'), 'minute', filename)
            else:
                filename = '%s%s' % (qdata[0].instrument.lisn_code, dt.strftime('%d%b.%ym'))
                if qdata[0].instrument.server.lower()=='montecillo':
                    path = os.path.join(path_mag_montecillo, code, dt.strftime('%Y'), filename.lower())
                elif qdata[0].instrument.server.lower()=='jicamarca':
                    path = os.path.join(path_mag_jro, '%s%02d' % (qdata[0].instrument.lisn_code, 
                                                                  dt.year%100), filename.lower())
                else:
                    path = '/path/to/file'
        else:
            path = '/path/to/file'
        data = MAGData(path)    
        ax = plotter.plot_mag(data, figname=output, figure=fig, scale=scale, station=st)
        ax.ax.set_xlabel('')
    ax.ax.set_xlabel('Hour [UTC]')
    if output=='web':
        return fig.show()
    elif output:
        fig.figure.savefig(output)    
    else:
        fig.show()

def plt_delta(code, date, output=None, scale=None):
    '''
    '''
    
    if code is None:
        fig = plt_error('Invalid parameters')
        if output=='web':
            return fig.show()
        else:
            print 'Invalid parameters'
            return
    
    if date is not None:
        dt = GPSDateTime(date).datetime
    else:
        dt = GPSDateTime().now().datetime
    
    code1,code2 = [s.strip() for s in code.split(',') if s][:2]
    
    
    qdata1 = Data.objects.select_related().filter(datatype__pk=1, 
                                                  instrument__code=code1)
    req1 = requests.get('http://localhost/django/utils/station/', 
                        params={'code':code1, 'instrument':'magnetometer'})
    st1 = req1.json()
    if qdata1:
        if date:
            filename = '%s_%s.min.gz' % (code1, dt.strftime('%y%m%d'))
            path1 = os.path.join(path_mag, qdata1[0].instrument.network, code1, dt.strftime('%Y/%m'), 'minute', filename)
        else:
            filename = '%s%s' % (qdata1[0].instrument.lisn_code, dt.strftime('%d%b.%ym'))
            if qdata1[0].instrument.server.lower()=='montecillo':
                path1 = os.path.join(path_mag_montecillo, code1, dt.strftime('%Y'), filename.lower())
            elif qdata1[0].instrument.server.lower()=='jicamarca':
                path1 = os.path.join(path_mag_jro, '%s%02d' % (qdata1[0].instrument.lisn_code, 
                                                              dt.year%100), filename.lower())
            else:
                path1 = '/path/to/file'
    else:
        path1 = '/path/to/file'
    data1 = MAGData(path1, st1)
    
    qdata2 = Data.objects.select_related().filter(datatype__pk=1, 
                                                  instrument__code=code2)
    req2 = requests.get('http://localhost/django/utils/station/', 
                        params={'code':code2, 'instrument':'magnetometer'})
    st2 = req2.json()
    if qdata2:
        if date:
            filename = '%s_%s.min.gz' % (code2, dt.strftime('%y%m%d'))
            path2 = os.path.join(path_mag, qdata2[0].instrument.network, code2, dt.strftime('%Y/%m'), 'minute', filename)
        else:
            filename = '%s%s' % (qdata2[0].instrument.lisn_code, dt.strftime('%d%b.%ym'))
            if qdata2[0].instrument.server.lower()=='montecillo':
                path2 = os.path.join(path_mag_montecillo, code2, dt.strftime('%Y'), filename.lower())
            elif qdata2[0].instrument.server.lower()=='jicamarca':
                path2 = os.path.join(path_mag_jro, '%s%02d' % (qdata2[0].instrument.lisn_code, 
                                                              dt.year%100), filename.lower())
            else:
                path2 = '/path/to/file'
    else:
        path2 = '/path/to/file'
    data2 = MAGData(path2, st2)
        
    plt = plotter.plot_deltaH(data1, data2, figname=output, scale=scale)        
    
    if output=='web':
        return plt
        
if __name__=='__main__':
    import time
    start = time.clock()
    #plt_delta(date='2013-08-31', code='jica,piur', output='./plot.png')
    plt_mag(date=None, code='jica', output='./plot.png')
    end = time.clock()
    print (end-start)*1000
